package com.witmore.neutron.ai.web.apiv2.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.apiv2.controller.vo.*;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.PermissionService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * V2 权限管理相关接口
 * Author: 豆子高
 * Date: 2025/1/2
 */
@Slf4j
@RestController
@RequestMapping("/v2/permission")
public class PermissionControllerV2 {

    @Autowired
    private PermissionService permissionService;

    /**
     * 分页查询权限列表
     */
    @RequiresPermission("permission:list")
    @PostMapping("/list")
    public ResponseResult<Page<PermissionResult>> getPermissionPage(@RequestBody PermissionQueryParam queryParam) {
        try {
            Page<PermissionResult> result = permissionService.getPermissionPage(queryParam);
            return ResponseResult.success(result);
        } catch (Exception e) {
            log.error("查询权限列表失败", e);
            return ResponseResult.fail(500, "查询权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取权限树形结构
     */
    @RequiresPermission("permission:tree")
    @GetMapping("/tree")
    public ResponseResult<List<PermissionResult>> getPermissionTree() {
        try {
            List<PermissionResult> result = permissionService.getPermissionTree();
            return ResponseResult.success(result);
        } catch (Exception e) {
            log.error("获取权限树失败", e);
            return ResponseResult.fail(500, "获取权限树失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取权限详情
     */
    @RequiresPermission("permission:detail")
    @GetMapping("/detail/{id}")
    public ResponseResult<PermissionResult> getPermissionById(@PathVariable("id") Long id) {
        try {
            PermissionResult result = permissionService.getPermissionById(id);
            if (result == null) {
                return ResponseResult.fail(404, "权限不存在");
            }
            return ResponseResult.success(result);
        } catch (Exception e) {
            log.error("获取权限详情失败", e);
            return ResponseResult.fail(500, "获取权限详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建权限
     */
    @RequiresPermission("permission:create")
    @PostMapping("/create")
    public ResponseResult<Boolean> createPermission(@Valid @RequestBody PermissionCreateParam createParam) {
        try {
            String creator = "system"; // 默认创建者，实际项目中应从会话中获取
            UserSession userSession = GlobalAccountSession.getUserInfo();
            if (userSession != null && userSession.getUserName() != null) {
                creator = userSession.getUserName();
            }
            boolean result = permissionService.createPermission(createParam, creator);
            if (result) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.fail(500, "权限创建失败");
            }
        } catch (Exception e) {
            log.error("创建权限失败", e);
            return ResponseResult.fail(500, "创建权限失败: " + e.getMessage());
        }
    }

    /**
     * 更新权限
     */
    @RequiresPermission("permission:update")
    @PostMapping("/update")
    public ResponseResult<Boolean> updatePermission(@Valid @RequestBody PermissionUpdateParam updateParam) {
        try {
            boolean result = permissionService.updatePermission(updateParam);
            if (result) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.fail(500, "权限更新失败");
            }
        } catch (Exception e) {
            log.error("更新权限失败", e);
            return ResponseResult.fail(500, "更新权限失败: " + e.getMessage());
        }
    }

    /**
     * 删除权限
     */
    @RequiresPermission("permission:delete")
    @PostMapping("/delete")
    public ResponseResult<Boolean> deletePermission(@Valid @RequestBody PermissionDeleteParam deleteParam) {
        try {
            boolean result = permissionService.deletePermission(deleteParam.getId());
            if (result) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.fail(500, "权限删除失败");
            }
        } catch (Exception e) {
            log.error("删除权限失败", e);
            return ResponseResult.fail(500, "删除权限失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除权限
     */
    @RequiresPermission("permission:batchDelete")
    @PostMapping("/batchDelete")
    public ResponseResult<Boolean> batchDeletePermission(@Valid @RequestBody PermissionBatchDeleteParam batchDeleteParam) {
        try {
            boolean result = permissionService.batchDeletePermission(batchDeleteParam.getIds());
            if (result) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.fail(500, "权限批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除权限失败", e);
            return ResponseResult.fail(500, "批量删除权限失败: " + e.getMessage());
        }
    }

    /**
     * 检查权限编码是否存在
     */
    @RequiresPermission("permission:checkCode")
    @GetMapping("/checkCode")
    public ResponseResult<Boolean> checkPermissionCode(@RequestParam("code") String code,
                                                       @RequestParam(value = "excludeId", required = false) Long excludeId) {
        try {
            boolean exists = permissionService.checkPermissionCodeExists(code, excludeId);
            return ResponseResult.success(exists);
        } catch (Exception e) {
            log.error("检查权限编码失败", e);
            return ResponseResult.fail(500, "检查权限编码失败: " + e.getMessage());
        }
    }
}
